package com.elitel.frame.business.controller;

import com.elitel.frame.base.service.SysPrjServiceService;
import com.elitel.frame.business.service.PolymerServerService;
import com.elitel.frame.main.entity.SysPrjservice;
import com.elitel.frame.main.entity.ext.DBServer;
import com.elitel.frame.main.entity.polym.CfgMultQueryField;
import com.elitel.frame.main.entity.polym.CfgMultResultField;
import com.elitel.frame.main.entity.vo.JsonDataResult;
import com.elitel.frame.main.entity.vo.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.ArrayStack;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.elitel.common.core.constant.RequestConstant.SERVICE_ID;

/**
 *
 * 聚合服务
 * @author hi_bj
 */
@Controller
@RequestMapping(value = "/business/polymerServer")
@Api(value = "/business/polymerServer", tags = "聚合服务接口")
public class PolymerServerController {
    private static final Logger logger = LoggerFactory.getLogger(PolymerServerController.class);
    @Autowired
    PolymerServerService polymerServerService;
    @Autowired
    SysPrjServiceService sysPrjServiceService;
    /**
     * 查询聚合服务
     * @param request
     * @param serviceID
     * @param pageNO
     * @param pageSize
     * @param conQuery
     * @param refCache
     * @return
     */
    @ApiOperation(value = "聚合服务查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = SERVICE_ID, value = "服务编码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageNO", value = "当前页码", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "conQuery", value = "查询条件集合", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "refCache", value = "是否强制刷新缓存", required = false, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/queryPolymerServer", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object queryPolymerServer(HttpServletRequest request,
                                     @RequestParam(value = SERVICE_ID) String serviceID,
                                     @RequestParam(value = "pageNO", defaultValue = "1") String pageNO,
                                     @RequestParam(value = "pageSize", defaultValue = "10") String pageSize,
                                     String conQuery,
                                     String refCache) {
        //记录分页信息，验证是否为非法参数
        String pagingNum, pagingSize;
        try {
            if (pageNO == null || pageNO.isEmpty()) {
                pageNO = "1";
            }
            if (pageSize == null || pageSize.isEmpty()) {
                pageSize = "10";
            }
            pagingNum = String.valueOf(Integer.parseInt(pageNO));
            pagingSize = String.valueOf(Integer.parseInt(pageSize));
        } catch (NumberFormatException e) {
            logger.error("非法参数：", e);
            return JsonDataResult.responseError("非法参数！");
        }
        return JsonDataResult.responseSuccess(polymerServerService.queryPolymerServer(request, serviceID, pagingNum, pagingSize, conQuery, refCache), null);
    }

    /**
     * 查看作为查询条件的字段
     * @param serviceID
     * @return
     */
    @ApiOperation(value = "根据服务id获取当前服务查询字段的集合", notes = "获取当前服务的查询字段")
    @RequestMapping(value = "/selectQueryFiled", method = RequestMethod.GET)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = SERVICE_ID,
                    value = "服务id",
                    required = true,
                    paramType = "query",
                    dataType = "String")
    })
    public Object selectQueryFiled(@RequestParam(value = SERVICE_ID) String serviceID) {
        JsonResult jsonResult = new JsonResult();
        List<CfgMultQueryField> queryFieldList = polymerServerService.selectQueryFiled(serviceID);
        List<Map<String, Object>> resultList = new ArrayList();
        Map<String, Object> fileCodeMap = new HashMap();
        queryFieldList.forEach(item -> {
            if (!fileCodeMap.containsKey(item.getNewFieldCode())) {
                fileCodeMap.put(item.getNewFieldCode(), null);
                Map<String, Object> map = new HashMap<>();
                map.put("fieldname", item.getNewFieldCode());
                map.put("fieldnamecn", item.getNewFieldName());
                resultList.add(map);
            }
        });
        jsonResult.setData(resultList);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询取当前服务显示字段
     * @param serviceID
     * @return
     */
    @ApiOperation(value = "根据服务id获取当前服务是否分页", notes = "获取当前服务是否分页")
    @RequestMapping(value = "/selectShowFiled", method = RequestMethod.GET)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = SERVICE_ID,
                    value = "服务id",
                    required = true,
                    paramType = "query",
                    dataType = "String")
    })
    public Object selectShowFiled(@RequestParam(value = SERVICE_ID) String serviceID) {
        JsonResult jsonResult = new JsonResult();
        List<CfgMultResultField> resultFieldList = polymerServerService.selectShowFiled(serviceID);
        List<Map<String,Object>> resultList = new ArrayList<>();
        Map<String, Object> fileCodeMap = new HashMap();
        resultFieldList.forEach(item -> {
            if (!fileCodeMap.containsKey(item.getNewFieldCode())) {
                fileCodeMap.put(item.getNewFieldCode(), null);
                Map<String, Object> map = new HashMap<>();
                map.put("fieldname", item.getNewFieldCode());
                String newFieldName = StringUtils.isEmpty(item.getNewFieldName())?item.getNewFieldCode():item.getNewFieldName();
                map.put("fieldnamecn", newFieldName);
                resultList.add(map);
            }
        });
        jsonResult.setData(resultList);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询分页状态
     *
     * @param serviceID
     * @return
     */
    @ApiOperation(value = "根据服务id获取当前服务是否分页", notes = "获取当前服务是否分页")
    @RequestMapping(value = "/selectPagingFlag", method = RequestMethod.GET)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = SERVICE_ID,
                    value = "服务id",
                    required = true,
                    paramType = "query",
                    dataType = "String")
    })
    public boolean selectPagingFlag(@RequestParam(value = SERVICE_ID) String serviceID) {
        boolean pagingFlag = false;
        if (sysPrjServiceService.getSysPrjserviceByServiceCode(serviceID).getPaginationFlag() == 1) {
            pagingFlag = true;
        }
        return pagingFlag;
    }
}
